package com.whfc.emp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.enums.EnableState;
import com.whfc.common.exception.BizException;
import com.whfc.common.geometry.GeometryUtil;
import com.whfc.common.geometry.Point;
import com.whfc.common.geometry.Polygon;
import com.whfc.common.result.ResultEnum;
import com.whfc.emp.constant.EmpConstant;
import com.whfc.emp.dao.AppEmpConfigMapper;
import com.whfc.emp.dao.AppSyncRealNameConfigDao;
import com.whfc.emp.dto.AppEmpConfigDTO;
import com.whfc.emp.dto.AppEmpSettingDTO;
import com.whfc.emp.dto.EmpValidFenceDTO;
import com.whfc.emp.entity.AppEmpConfig;
import com.whfc.emp.entity.AppSyncRealNameConfig;
import com.whfc.emp.enums.AttendType;
import com.whfc.emp.manager.CommonEmpConfigManager;
import com.whfc.emp.param.AppEmpSettingAddParam;
import com.whfc.emp.realNamePlatform.jingZhou.JINGZHOUApi;
import com.whfc.emp.service.AppEmpConfigService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClasssName AppEmpConfigServiceImpl
 * @Description 人员配置项服务
 * @Author hw
 * @Date 2020/12/16 17:33
 * @Version 1.0
 */
@DubboService(interfaceClass = AppEmpConfigService.class, version = "1.0.0", timeout = 5000)
public class AppEmpConfigServiceImpl implements AppEmpConfigService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppEmpConfigMapper appEmpConfigMapper;

    @Autowired
    private CommonEmpConfigManager commonEmpConfigManager;

    @Autowired
    private AppSyncRealNameConfigDao appSyncRealNameConfigDao;

    @Override
    public AttendType getAttendType(Integer deptId) {
        logger.info("获取考勤方式，deptId:{}", deptId);
        return commonEmpConfigManager.getAttendType(deptId);
    }

    @Override
    public void setAttendType(Integer deptId, AttendType attendType) {
        logger.info("设置考勤方式,deptId:{},attendType：{}", deptId, attendType);
        if (attendType != null) {
            AppEmpConfig empConfig = appEmpConfigMapper.selectByDeptIdAndCode(deptId, EmpConstant.EMP_ATTEND_CODE);
            if (empConfig != null) {
                empConfig.setValue(String.valueOf(attendType.getValue()));
                appEmpConfigMapper.updateByPrimaryKeySelective(empConfig);
            } else {
                empConfig = new AppEmpConfig();
                empConfig.setDeptId(deptId);
                empConfig.setCode(EmpConstant.EMP_ATTEND_CODE);
                empConfig.setValue(String.valueOf(attendType.getValue()));
                appEmpConfigMapper.insertSelective(empConfig);
            }
        }
    }

    @Override
    public boolean isIdCardVerify(Integer deptId) {
        logger.info("项目是否需要开启人脸识别,deptId:{}", deptId);
        return commonEmpConfigManager.isIdCardVerify(deptId);
    }

    @Override
    public AppEmpSettingDTO getSetting(Integer deptId) {
        logger.info("查询项目的人员配置,deptId:{}", deptId);
        return commonEmpConfigManager.getSetting(deptId);
    }

    @Override
    public void settingAdd(AppEmpSettingAddParam request) {
        logger.info("添加人员实名制设置,request：{}", request);
        Integer deptId = request.getDeptId();
        Integer childLabourAge = request.getChildLabourAge();
        Integer childLabourAgeFlag = request.getChildLabourAgeFlag();
        Integer empBlackListFlag = request.getEmpBlackListFlag();
        Integer femaleRetireAge = request.getFemaleRetireAge();
        Integer femaleRetireAgeFlag = request.getFemaleRetireAgeFlag();
        Integer maleRetireAge = request.getMaleRetireAge();
        Integer maleRetireAgeFlag = request.getMaleRetireAgeFlag();
        Integer qrFlag = request.getQrFlag();
        Integer empQrFlag = request.getEmpQrFlag();
        Integer minutes = request.getMinutes();
        String qr = request.getQr();

        List<AppEmpConfig> list = new ArrayList();
        if (childLabourAge != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setValue(String.valueOf(childLabourAge));
            appEmpConfig.setCode(EmpConstant.CHILD_LABOUR_AGE);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(childLabourAgeFlag);
            list.add(appEmpConfig);
        }
        if (maleRetireAge != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setValue(String.valueOf(maleRetireAge));
            appEmpConfig.setCode(EmpConstant.MALE_RETIRE_AGE);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(maleRetireAgeFlag);
            list.add(appEmpConfig);
        }
        if (femaleRetireAge != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setValue(String.valueOf(femaleRetireAge));
            appEmpConfig.setCode(EmpConstant.FEMALE_RETIRE_AGE);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(femaleRetireAgeFlag);
            list.add(appEmpConfig);
        }
        if (empBlackListFlag != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setCode(EmpConstant.EMP_BLACK_LIST);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(empBlackListFlag);
            appEmpConfig.setValue("");
            list.add(appEmpConfig);
        }
        if (qrFlag != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setCode(EmpConstant.ATTEND_QR);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(qrFlag);
            appEmpConfig.setValue(qr);
            list.add(appEmpConfig);
        }
        if (empQrFlag != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setCode(EmpConstant.EMP_QR);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(empQrFlag);
            appEmpConfig.setValue(qr);
            list.add(appEmpConfig);
        }
        if (minutes != null) {
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setValue(String.valueOf(minutes));
            appEmpConfig.setCode(EmpConstant.TIME_OUT);
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setEnableFlag(EnableState.ENABLED.getValue());
            list.add(appEmpConfig);
        }
        if (list.size() > 0) {
            appEmpConfigMapper.insertOrUpdate(list);
        }
    }


    @Override
    public void saveQr(Integer deptId, String qrPath, String empConstant) {
        logger.info("下载考勤二维码,deptId：{},qrPath:{}", deptId, qrPath);
        AppEmpConfig appEmpConfig = appEmpConfigMapper.selectByDeptIdAndCode(deptId, empConstant);
        if (appEmpConfig == null) {
            appEmpConfig = new AppEmpConfig();
            // 生成二维码
            appEmpConfig.setValue(qrPath);
            appEmpConfig.setEnableFlag(EnableState.DISABLED.getValue());
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setCode(empConstant);
            appEmpConfigMapper.insertSelective(appEmpConfig);
        }
    }

    @Override
    public boolean checkQr(Integer deptId, String empConstant) {
        logger.info("验证考勤二维码是否启用,deptId:{}", deptId);
        AppEmpConfig appEmpConfig = appEmpConfigMapper.selectByDeptIdAndCode(deptId, empConstant);
        if (appEmpConfig == null || EnableState.DISABLED.getValue().equals(appEmpConfig.getEnableFlag())) {
            return false;
        }
        return true;
    }

    @Override
    public List<EmpValidFenceDTO> getEmpValidFenceList(Integer deptId) {
        List<EmpValidFenceDTO> list = new ArrayList<>();
        AppEmpConfig appEmpConfig = appEmpConfigMapper.selectByDeptIdAndCode(deptId, EmpConstant.FENCE);
        EmpValidFenceDTO empValidFenceDTO = new EmpValidFenceDTO();
        if (appEmpConfig != null) {
            String value = appEmpConfig.getValue();
            if (value.startsWith("POLYGON")) {
                Polygon polygon = GeometryUtil.decodePolygon(value);
                empValidFenceDTO.setPolygonPointList(polygon.getPointList());
            } else if (value.startsWith("MULTIPOLYGON")) {
                List<List<Point>> multiPolygon = GeometryUtil.decodeMultiPolygon(value);
                empValidFenceDTO.setMultiPolygonPointList(multiPolygon);
            }
            empValidFenceDTO.setCode(EmpConstant.FENCE);
            list.add(empValidFenceDTO);
        }
        return list;
    }


    @Override
    public void setEmpValidFence(Integer deptId, List<EmpValidFenceDTO> list) {
        //删除旧数据
        appEmpConfigMapper.delByDeptIdAndCode(deptId, EmpConstant.FENCE);
        //保存新数据
        if (list != null && !list.isEmpty()) {
            EmpValidFenceDTO empValidFenceDTO = list.get(0);
            AppEmpConfig appEmpConfig = new AppEmpConfig();
            appEmpConfig.setDeptId(deptId);
            appEmpConfig.setCode(EmpConstant.FENCE);
            List<Point> polygonPointList = empValidFenceDTO.getPolygonPointList();
            List<List<Point>> multiPolygonPointList = empValidFenceDTO.getMultiPolygonPointList();
            String polygonKwt;
            if (polygonPointList != null && !polygonPointList.isEmpty()) {
                Polygon polygon = new Polygon();
                polygon.setPointList(polygonPointList);
                polygonKwt = GeometryUtil.encodePolygon(polygon);
                appEmpConfig.setValue(polygonKwt);
            } else if (multiPolygonPointList != null && !multiPolygonPointList.isEmpty()) {
                String multiPolygon = GeometryUtil.encodeMultiPolygon(multiPolygonPointList);
                appEmpConfig.setValue(multiPolygon);
            } else {
                //数据为空
                return;
            }
            appEmpConfigMapper.insertSelective(appEmpConfig);
        }
    }

    @Override
    public AppEmpConfigDTO getEmpConfig(Integer deptId, String code) throws BizException {
        if (deptId == null || StringUtils.isBlank(code)) {
            return null;
        }
        AppEmpConfig appEmpConfig = appEmpConfigMapper.selectByDeptIdAndCode(deptId, code);
        if (appEmpConfig == null) {
            return null;
        }
        AppEmpConfigDTO appEmpConfigDTO = new AppEmpConfigDTO();
        BeanUtils.copyProperties(appEmpConfig, appEmpConfigDTO);
        return appEmpConfigDTO;
    }

    @Override
    public void addSyncRealNameConfig(AppSyncRealNameConfig request) throws BizException {
        if (request.getDeptId()==null) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"deptId不能为空");
        }
        if (StringUtils.isBlank(request.getPlatform())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"推送平台不能为空");
        }
        AppSyncRealNameConfig appSyncRealNameConfig = appSyncRealNameConfigDao.selectByDeptIdAndPlatform(request.getDeptId(), request.getPlatform());
        if (appSyncRealNameConfig!=null) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"该平台已存在");
        }
        if (StringUtils.isBlank(request.getGdmCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"工地码不能为空");
        }
        if (StringUtils.isBlank(request.getAppId())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"appId不能为空");
        }
        if (StringUtils.isBlank(request.getAppSecret())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"appSecret不能为空");
        }
        if (StringUtils.isBlank(request.getPushUrl())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"推送地址不能为空");
        }
        if ("jingzhou".equals(request.getPlatform())) {
            JSONObject engInfo = JINGZHOUApi.getEngInfo(request);
            if (0!=engInfo.getInteger("code")) {
                throw new BizException(ResultEnum.FAILURE.getCode(),"参数错误,无法初始化配置");
            }
            JSONArray data = engInfo.getJSONArray("data");
            if (data.size() < 1) {
                throw new BizException(ResultEnum.FAILURE.getCode(),"无项目编码");
            }
            JSONObject json = (JSONObject)data.get(0);
            String projectCode = json.getString("projectCode");
            request.setProjectCode(projectCode);
            appSyncRealNameConfigDao.insertSelective(request);
            return;
        }
        throw new BizException(ResultEnum.FAILURE.getCode(),"无效配置");
    }

    @Override
    public void editSyncRealNameConfig(AppSyncRealNameConfig request) {
        AppSyncRealNameConfig appSyncRealNameConfig = appSyncRealNameConfigDao.selectByDeptIdAndPlatform(request.getDeptId(), request.getPlatform());
        if (appSyncRealNameConfig!= null && !request.getId().equals(appSyncRealNameConfig.getId())) {
            throw new BizException(ResultEnum.FAILURE.getCode(),"编辑失败,该平台已存在");
        }
        if ("jingzhou".equals(request.getPlatform())) {
            JSONObject engInfo = JINGZHOUApi.getEngInfo(request);
            if (0!=engInfo.getInteger("code")) {
                throw new BizException(ResultEnum.FAILURE.getCode(),"参数错误,无法初始化配置");
            }
            JSONArray data = engInfo.getJSONArray("data");
            if (data.size() < 1) {
                throw new BizException(ResultEnum.FAILURE.getCode(),"无项目编码");
            }
            JSONObject json = (JSONObject)data.get(0);
            String projectCode = json.getString("projectCode");
            request.setProjectCode(projectCode);
            appSyncRealNameConfigDao.updateByPrimaryKeySelective(request);
        }
        throw new BizException(ResultEnum.FAILURE.getCode(),"无效配置");
    }

    @Override
    public void delSyncRealNameConfig(AppSyncRealNameConfig request) {
        appSyncRealNameConfigDao.deleteByPrimaryKey(request.getId());
    }

    @Override
    public List<AppSyncRealNameConfig> listSyncRealNameConfig(AppSyncRealNameConfig request) {
        return appSyncRealNameConfigDao.selectList(request.getDeptId());
    }


}
